<script setup lang="ts">
import {reactive, ref, onMounted, onUnmounted} from "vue";
import {dataList, dataSubmit, dataInsert, dataInfo} from "@/api/examine";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {useStorage} from "@/hooks/web/useStorage";
import {useDevice} from "@/hooks/web/useDevice";

const {mobile} = useDevice()
const {getStorage} = useStorage()
const isAdmin = getStorage('userInfo').is_admin
const loading = ref(true)
let is_completed = ref('')
const activeName = ref('1')
const examineType = ref(0)
const quizTime = ref('')
const saveLoad = ref(false)
const submitLoad = ref(false)
let timer = ''  //计时器对象
const currentCountdown = ref('')
const examineList = reactive({data: [], is_start: '', exam_time: ''})
const examineInfo = ref({})
const remainingTime = ref()
//获取在线考试数据
const fetchData = async () => {
  let res = await dataList();
  loading.value = false
  if (res) {
    examineList.data = res.data.list
    examineList.is_start = res.data.is_start
    examineList.exam_time = res.data.exam_time
    quizTime.value = res.data.time
    currentCountdown.value = res.data.time
    is_completed.value = res.data.is_completed
    if (is_completed.value == 1) {
      activeName.value = '2'
      if (isAdmin || !quizTime.value) return
      timer = setInterval(updateDisplay, 1000);
    } else {
      let res = await dataInfo();
      examineInfo.value = res.data
      activeName.value = '1'
    }
  }
}

const handleSave = async () => {
  if (!examineList.is_start){
  return   ElMessage({message: '还未到考试开始时间,禁止保存', type: 'warning'})
  }
  try {
    saveLoad.value = true
    let res = await dataInsert(examineList);
    saveLoad.value = false
    if (res) {
      ElMessage({message: '保存成功', type: 'success'})
      clearInterval(timer)
      await fetchData();
    }
  } catch (e) {
    saveLoad.value = false
  }
}

const handleSubmit = () => {
  if (!examineList.is_start){
    return   ElMessage({message: '还未到考试开始时间,禁止交卷', type: 'warning'})
  }
  ElMessageBox.confirm('是否交卷,一旦提交无法更改', '提示', {type: 'warning'}).then(async () => {
    try {
      saveLoad.value = true
      let res = await dataSubmit(examineList);
      saveLoad.value = false
      if (res) {
        ElMessage({message: '交卷成功', type: 'success'})
        await fetchData();
      }
    } catch (err) {
      saveLoad.value = false
    }

  }).catch(() => {
  })
}

const handleChange = (type, sectionId) => {
  examineType.value = type
  document.getElementById(sectionId).scrollIntoView(false);
}


const handleFinish = async () => {
  if (!quizTime.value) return
  submitLoad.value = true
  let res = await dataSubmit(examineList);
  submitLoad.value = false
  if (res) {
    ElMessage({
      message: '答题时间已结束,已自动交卷',
      type: 'warning',
      duration: 0,
      showClose: true,
    })
    await fetchData();
  }
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const changeOptions = [
  {
    label: 'TEXT A',
    element: 'text0'
  },
  {
    label: 'TEXT B',
    element: 'text1'
  },
  {
    label: 'TEXT C',
    element: 'text2'
  },
  {
    label: 'TEXT D',
    element: 'text3'
  },
  {
    label: '书面写作',
    element: 'text4'
  },
]

let duration = 5 * 60 * 1000;
let notice = false
const countdown = () => {
  // 目标时间戳（例如：2023年1月1日0点）
  var targetTime =   currentCountdown.value
  // 当前时间戳
  var currentTime = new Date().getTime();
  // 时间差（单位：毫秒）
  var timeDifference = targetTime - currentTime;

  // 如果时间差为负数，意味着目标时间已过，显示00:00:00
  if (timeDifference < 0) {
    console.log('结束')
    handleFinish()
    clearInterval(timer)
  } else if (timeDifference <= duration && !notice) {
    notice = true
    ElNotification({
      title: '提示',
      message: '答题剩余时间小于5分钟',
      type: 'warning',
      duration: 0,
      showClose: true,
    })
  }

  // 计算剩余时间
  var hours = Math.floor((timeDifference / (1000 * 60 * 60)) % 24);
  var minutes = Math.floor((timeDifference / (1000 * 60)) % 60);
  var seconds = Math.floor((timeDifference / 1000) % 60);

  // 补零操作
  hours = (hours < 10 ? '0' : '') + hours;
  minutes = (minutes < 10 ? '0' : '') + minutes;
  seconds = (seconds < 10 ? '0' : '') + seconds;

  return {
    hours: hours,
    minutes: minutes,
    seconds: seconds
  };
}

const updateDisplay = () => {
  var time = countdown();
   remainingTime.value = time.hours + ":" + time.minutes + ":" + time.seconds;
}

onMounted(() => {
  fetchData()
})

onUnmounted(() => {
  clearInterval(timer)
})

</script>
<template>
  <el-row justify="center" v-if="is_completed==2">
    <el-col :lg="18" :xs="24">
      <el-tabs
          v-model="activeName"
          type="card"
          class="demo-tabs"
          @tab-click="handleClick"
      >
        <el-tab-pane label="考试信息" name="1"></el-tab-pane>
        <el-tab-pane label="查看试卷" name="2">
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <el-col class="exam-descriptions" :lg="18" :xs="24" v-show="activeName==1">
      <div class="notice">您的试卷已提交,请耐心等待监考老师评分~</div>
      <el-descriptions title="考试信息" border :column="mobile?1:2">
        <el-descriptions-item label="姓名">{{ examineInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="准考证号码">{{ examineInfo.exam_num }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ examineInfo.idnum }}</el-descriptions-item>
        <el-descriptions-item label="交卷时间">{{ examineInfo.time }}</el-descriptions-item>
      </el-descriptions>
    </el-col>
  </el-row>
  <el-row style="margin-bottom:60px" v-loading="loading"
          v-show="activeName==2">
    <template v-for="(item,index) in examineList.data">
      <el-col class="left-container" :lg="13" :xs="24" :sm="17" v-show="item.type ==='read'">
        <el-col :lg="24" class="examine-wrap " style="margin-top: 30px" :id="item.type ==='read' ?'text'+index:''">
          <div class="text-box">
            <template v-if="!index">
              <p class="bold">暨南大学经济学院</p>
              <p class="bold">2+2+1本硕留学 2024级新生入学笔试</p>
            </template>
            <p class="bold bold1">{{ item.title }}</p>
            <el-divider/>
            <div v-html="item.content"></div>
          </div>
        </el-col>
        <el-col :lg="24" class="examine-wrap">
          <el-form label-position="top">
            <div class="single">
              <span></span>
              单选题
            </div>
            <el-divider/>
            <el-form-item v-for="(item1,index1) in item.child" :label="item1.content">
              <el-radio-group class="examine-radio ml-4" v-model="item1.answer">
                <el-radio v-for="(item2,index2) in item1.child" :key="index2" :value="item2.label"
                          size="large">
                  {{ item2.content }}
                </el-radio>
              </el-radio-group>
              <el-divider/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-col>
      <el-col class="left-container" :lg="13" :xs="24" :sm="17" v-show="item.type ==='write'">
        <el-col :lg="24" class="examine-wrap" style="margin-top: 30px" :id="item.type ==='write'?'text'+index:''">
          <div class="text-box">
            <p class="bold bold1">书面写作</p>
            <el-divider/>
            <div v-html="item.content"></div>
          </div>
        </el-col>
        <el-col :lg="24" class="examine-wrap">
          <el-form label-position="top">
            <div class="single">
              <span></span>
              写作题
            </div>
            <el-divider/>
            <el-form-item label="答:">
              <el-input v-model="item.answer" type="textarea" :rows="10" placeholder="请输入..."></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-col>
    </template>
    <div class="right-container">
      <div class="right-wrap">
        <div class="time time-start right-fixed" v-if="is_completed==1 && !isAdmin">
          <el-statistic class="start-time" title="答题开始时间" :value="examineList.exam_time"/>
        </div>
        <div class="time right-fixed" v-if="is_completed==1 && examineList.is_start">
          <p>答题剩余时间</p>
          <p>{{remainingTime}}</p>
        </div>
        <div class="right-fixed" v-loading="saveLoad">
          <div class="single">
            <span></span>
            答题卡
          </div>
          <el-divider/>
          <div class="option-wrap">
            <div v-for="(item,index) in changeOptions" @click="handleChange(index,item.element)"
                 :class="{active:examineType==index}">
              {{ item.label }}
            </div>
          </div>
          <el-divider/>
          <div class="btn-wrap" v-if="is_completed==1 && !isAdmin">
            <div class="sub-btn" @click="handleSave">
              保存答案
            </div>
            <div class="sub-btn" @click="handleSubmit">
              交 卷
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-row>
</template>
<style scoped lang="less">

//试卷提交之后的样式 S
.exam-descriptions {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 40px 20px;
  border-radius: 3px;

  .notice {
    margin-bottom: 20px;
    color: #F56C6C;
    font-weight: bold;
  }

  .grade-num {
    color: #FF571B;
    font-size: 15px;
    font-weight: bold;
  }
}

//试卷提交之后的样式 E

.analyse-wrap {
  .over {
    font-weight: bold;
    font-size: 17px;
  }

  .analyse-base {
    display: flex;
    justify-content: center;
    //align-items: center;
    margin-top: 40px;


    .analyse-line {
      width: 1px;
      height: 150px;
      background-color: #DCDFE6;
      margin: 0 30px;
    }
  }

  background-color: #fff;
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 0 auto 0;
  text-align: center;
  padding: 60px 0;
  border-radius: 5px;

  .grade {
    color: #FF571B;
    margin: 20px 0;
    font-family: "PingFang SC", "Hiragino Sans GB";

    span:nth-child(1) {
      font-size: 70px;
    }
  }

  .grade-wrap {
    display: flex;
    justify-content: center;
    align-items: center;

    .line {
      width: 1px;
      height: 30px;
      background-color: #DCDFE6;
      margin: 0 40px;
    }

    .grade-item {
      div:nth-child(2) {
        color: #1660FF;
        font-weight: bold;
        font-size: 17px;
        margin-top: 10px;
      }
    }
  }
}

.el-tabs {
  background-color: #fff;
  padding: 5px;
  margin-bottom: 10px;
}

.left-container {
  margin-left: 12.5%;
}

.right-container {
  position: relative;

  .right-wrap {
    width: 16%;
    position: fixed;
    z-index: 1;
    top: 176px;
    left: 70.7%;
  }
}


.right-fixed {
  padding: 20px;
  background-color: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;

  .option-wrap {
    display: flex;
    flex-wrap: wrap;

    .active {
      background-color: #67C23A;
      color: #fff;
      border: none;
    }

    div {
      cursor: pointer;
      padding: 5px;
      font-size: 12px;
      margin-right: 8px;
      margin-bottom: 5px;
      border-radius: 3px;
      text-align: center;
      border: 1px solid #CDD0D6;
    }
  }

  .btn-wrap {
    display: flex;
    flex-wrap: wrap;
    .sub-btn{
      padding: 6px 15px;
      font-size: 14px;
      background-color: #2DAE49;
      color: #fff;
      border-radius: 20px;
      margin-right: 10px;
      margin-bottom: 10px;
      cursor: pointer;
    }
  }
}

/deep/ .start-time {
  .el-statistic__head {
    text-align: center;
  }

  .el-statistic__number {
    font-size: 16px !important;
  }
}

.time {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  p:nth-child(1){
    margin-bottom: 5px;
    font-size: 12px;
  }

  .el-icon {
    margin-right: 10px;
  }
}

.time-start {
  margin-bottom: 10px;
}

.single {
  font-weight: bold;
  display: flex;
  align-items: center;
  font-size: 17px;

  span {
    display: inline-block;
    width: 4px;
    height: 15px;
    margin-right: 10px;
    background-color: #2DAE49;
  }

}

p {
  margin: 0;
}

.examine-wrap {
  background-color: #fff;
  padding: 30px;
  border-radius: 2px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.text-box {
  .bold {
    color: #303133;
    font-size: 19px;
    line-height: 30px;
    font-weight: bold;
    text-align: center;
  }

  .bold1 {
    margin-bottom: 20px;
    text-align: left;
    margin-top: 20px;
    font-size: 16px;
  }

  font-size: 15px;
  line-height: 30px;
  color: #606266;
}

.el-form {
  color: #303133;
  font-size: 18px !important;
}

/deep/ .el-form-item__label {
  font-size: 16px;
  color: #303133;
  //font-weight: bold;
}

/deep/ .el-radio {
  margin-bottom: 10px;
}

/deep/ .el-radio.el-radio--large .el-radio__label {
  font-size: 16px;
  text-overflow: ellipsis;
  white-space: normal;
  line-height: 20px;
  vertical-align: middle;
  display: inline-block;
}

.examine-radio {
  display: flex;
  flex-direction: column;
  align-items: normal;

  .el-radio:last-child {
    margin-right: auto;
  }
}

.el-scrollbar {
  background-color: #fff;
}

@size: 15px;
@media screen and(max-width: 768px) {
  .right-container {
    position: static;
    width: 100%;
    margin-top: 30px;

    .right-wrap {
      width: 100%;
      position: static;
      z-index: 1;
    }
  }

  .left-container {
    margin-left: 0;
  }

  .text-box {
    .bold {
      font-size: 20px;
    }

    font-size: @size;
  }


  .el-form {
    color: #303133;
  }

  /deep/ .el-form-item__label {
    font-size: @size;
  }

  /deep/ .el-radio.el-radio--large {
    margin-bottom: 14px;
  }

  /deep/ .el-radio.el-radio--large .el-radio__label {
    font-size: 14px;
    white-space: normal; /* 换行 */
  }

  /deep/ .el-form-item--default .el-form-item__content {
    line-height: 20px;
  }

}

@media screen and (max-width: 1199px) and (min-width: 769px) {
  .right-container {
    margin-top: 30px;
    width: 25%;

    .right-wrap {
      width: 25%;
      left: 73%;
      z-index: 1;
    }
  }

  .left-container {
    margin-left: 0;
  }

}

</style>